<template>
  <div class="job-entering-form">
    <BasicForm @register="register" @get="getFormData" class="basicForm">
      <template #add>
        <n-button @click="addSplitAndTask">新增</n-button>
      </template>
      <template #taskAndSplit>
        <div>
          <div v-for="(item, index) in formChild" :key="index" class="form-item-container">
            <div v-if="index !== 0" class="halving-line"></div>
            <div class="form-row">
              <n-form
                ref="formElRef"
                :model="item"
                :rules="ruleList[index]"
                :label-width="105"
                label-placement="left"
              >
                <n-grid :cols="2">
                  <FormItemGridItem label="是否连挂" path="whetherLinking">
                    <n-radio-group
                      v-model:value="item.whetherLinking"
                      @update:value="(val) => whetherLinkingUpdate(val, item, ruleList[index])"
                    >
                      <n-space>
                        <n-radio :value="false" label="不连挂" />
                        <n-radio :value="true" label="连挂" />
                      </n-space>
                    </n-radio-group>
                  </FormItemGridItem>

                  <FormItemGridItem label="股道" path="trackId">
                    <n-select
                      v-model:value="item.trackId"
                      @update:value="(val) => getTrackParking(val, item)"
                      placeholder="请选择"
                      label-field="trackName"
                      value-field="trackId"
                      filterable
                      clearable
                      :options="trackOptions"
                    />
                  </FormItemGridItem>

                  <FormItemGridItem v-if="!item.whetherLinking" label="编组" path="groupName">
                    <n-input
                      v-model:value="item.groupName"
                      :disabled="item.whetherLinking"
                      clearable
                      maxlength="32"
                      placeholder="请输入"
                    />
                  </FormItemGridItem>

                  <FormItemGridItem v-else label="编组" path="groupId">
                    <n-select
                      v-model:value="item.groupId"
                      @update:value="(val) => handelSelectGroup(val, item)"
                      label-field="groupName"
                      value-field="groupId"
                      :disabled="!item.whetherLinking"
                      placeholder="请选择"
                      filterable
                      clearable
                      :options="item.trackParkingOptions"
                    />
                  </FormItemGridItem>

                  <FormItemGridItem label="作业班组" path="teamId">
                    <n-select
                      v-model:value="item.teamId"
                      @update:value="(val) => (item.teamId = val)"
                      placeholder="请选择"
                      label-field="groupName"
                      value-field="groupId"
                      filterable
                      clearable
                      :options="groupOptions"
                    />
                  </FormItemGridItem>

                  <FormItemGridItem label="车辆数" path="carriageNumber">
                    <n-input-number
                      v-model:value="item.carriageNumber"
                      @update:value="(val) => (item.carriageNumber = val)"
                      placeholder="请输入"
                      :min="1"
                      :max="127"
                      :precision="0"
                    />
                  </FormItemGridItem>

                  <FormItemGridItem label="截止时间" path="taskTime">
                    <n-date-picker
                      v-model:formatted-value="item.taskTime"
                      @update:formatted-value="(val) => (item.taskTime = val)"
                      placeholder="请选择"
                      placement="bottom-end"
                      type="datetime"
                      clearable
                      value-format="yyyy-MM-dd HH:mm:ss"
                    />
                  </FormItemGridItem>
                </n-grid>
              </n-form>
              <n-button
                v-if="formChild.length > 1"
                type="error"
                secondary
                @click="() => formChild.splice(index, 1)"
                style="margin-left: 20px"
              >
                删除
              </n-button>
            </div>
          </div>
        </div>
      </template>
    </BasicForm>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue';
  import { BasicForm, FormSchema, useForm } from '@/components/Form';
  import FormItemGridItem from '@/components/Form/src/components/FormItemGridItem.vue';
  import { getTrackParkingList } from '@/api/home/parking';

  // 定义组件属性
  const props = defineProps({
    directionOptions: {
      type: Array as () => Array<{ label: string; value: string }>,
      default: () => [],
    },
    trackOptions: {
      type: Array as () => Array<any>,
      default: () => [],
    },
    groupOptions: {
      type: Array as () => Array<any>,
      default: () => [],
    },
  });

  // 响应式数据
  const formElRef = ref<any[]>([]);
  const formChild = ref<any[]>([]);
  const ruleList = ref<any[]>([]);

  // 表单规则
  const rules = reactive({
    carriageNumber: {
      type: 'number',
      required: true,
      message: '请输入车辆数',
      trigger: ['blur', 'submit'],
    },
    groupId: {
      type: 'string',
      required: false,
      message: '请选择编组',
      trigger: ['change', 'submit'],
    },
    groupName: {
      type: 'string',
      required: true,
      message: '请输入编组名称',
      trigger: ['blur', 'submit'],
    },
    trackId: {
      type: 'string',
      required: true,
      message: '请选择股道名称',
      trigger: ['change', 'submit'],
    },
    teamId: {
      type: 'string',
      required: true,
      message: '请选择班组',
      trigger: ['change', 'submit'],
    },
  });

  // 默认表单项
  const defaultFormItem = {
    carriageNumber: undefined,
    defensiveWay: undefined,
    groupId: undefined,
    groupName: undefined,
    stationId: undefined,
    orgId: undefined,
    taskTime: undefined,
    teamId: undefined,
    trackId: undefined,
    whetherLinking: false,
    trackParkingOptions: [],
  };

  // 表单配置
  const schemas: FormSchema[] = [
    {
      field: 'trainNumber',
      component: 'NInput',
      label: '车次',
      labelMessage: '',
      giProps: {
        span: 1,
      },
      rules: [
        {
          required: true,
          message: '请输入车次',
          trigger: ['blur', 'submit'],
        },
      ],
      componentProps: {
        maxlength: 32,
      },
    },
    {
      field: 'carriageNumber',
      component: 'NInputNumber',
      label: '车辆数',
      labelMessage: '',
      giProps: {
        span: 1,
      },
      componentProps: {
        placeholder: '请输入',
        min: 1,
        max: 127,
        precision: 0,
      },
      rules: [
        {
          required: true,
          type: 'number',
          message: '请输入车辆数',
          trigger: ['blur', 'submit'],
        },
      ],
    },
    {
      field: 'enteringTime',
      component: 'NDatePicker',
      label: '进站时间',
      labelMessage: '',
      giProps: {
        span: 1,
      },
      componentProps: {
        type: 'datetime',
      },
      rules: [
        {
          required: true,
          message: '请选择进站时间',
          trigger: ['change', 'submit'],
        },
      ],
    },
    {
      field: 'departureTimeExpected',
      component: 'NDatePicker',
      label: '预计离站时间',
      labelMessage: '',
      giProps: {
        span: 1,
      },
      componentProps: {
        type: 'datetime',
      },
    },
    {
      field: 'direction',
      component: 'NSelect',
      label: '停车方向',
      labelMessage: '',
      giProps: {
        span: 1,
      },
      componentProps: {
        multiple: false,
        filterable: true,
        remote: true,
        labelField: 'label',
        valueField: 'value',
        options: props.directionOptions,
      },
      rules: [
        {
          required: true,
          message: '请选择停车方向',
          trigger: ['change', 'submit'],
        },
      ],
    },
    {
      field: 'remark',
      component: 'NInput',
      label: '备注',
      labelMessage: '',
      giProps: {
        span: 1,
      },
      componentProps: {
        maxlength: 32,
      },
    },
    {
      slot: 'add',
      field: 'splitAndTaskAdd',
      label: '车编组',
      giProps: {
        span: 2,
      },
    },
    {
      slot: 'taskAndSplit',
      field: 'splitAndTaskList',
      label: '编组信息',
      giProps: {
        span: 2,
      },
    },
  ];

  // 初始化表单
  const [register, { submit, setFieldsValue }] = useForm({
    gridProps: {
      cols: 2,
    },
    labelWidth: 120,
    layout: 'horizontal',
    showActionButtonGroup: false,
    schemas,
  });

  // 获取表单数据
  async function getFormData() {
    return await submit();
  }

  // 设置表单数据
  async function setFormData(data: any) {
    await setFieldsValue(data);

    if (data.groupAndTaskList) {
      formChild.value = [];
      ruleList.value = [];

      const trackParkingMap: Record<string, any[]> = {};

      for (const item of data.groupAndTaskList) {
        if (item.isDefensiveTask) {
          const newItem = { ...item };

          if (newItem.trackId) {
            if (!(newItem.trackId in trackParkingMap)) {
              trackParkingMap[newItem.trackId] = await getTrackParkingList({
                trackId: newItem.trackId,
              });
            }
            newItem.trackParkingOptions = trackParkingMap[newItem.trackId];
          } else {
            newItem.trackParkingOptions = [];
          }

          formChild.value.push(newItem);
          ruleList.value.push({ ...rules });
        }
      }
    } else {
      formChild.value = [{ ...defaultFormItem }];
      ruleList.value = [{ ...rules }];
    }
  }

  // 新增编组和任务
  function addSplitAndTask() {
    formChild.value.push({ ...defaultFormItem });
    ruleList.value.push({ ...rules });
  }

  // 更新是否连挂状态
  function whetherLinkingUpdate(value: boolean, item: any, rule: any) {
    item.whetherLinking = value;
    item.groupId = null;
    item.groupName = null;
    rule.groupId.required = value;
    rule.groupName.required = !value;
  }

  // 处理选择编组
  function handelSelectGroup(value: string, item: any) {
    const selected = item.trackParkingOptions.find((opt: any) => opt.groupId == value);
    if (selected) {
      item.groupName = selected.groupName;
    }
  }

  // 获取股道停车信息
  async function getTrackParking(trackId: string, item: any) {
    item.trackParkingOptions = await getTrackParkingList({
      trackId: trackId,
    });
  }

  // 暴露方法给父组件
  defineExpose({
    submit: getFormData,
    setFormData,
    formElRef,
  });
</script>

<style scoped>
  .job-entering-form {
    width: 100%;
  }

  .form-item-container {
    display: flex;
    flex-direction: column;
  }

  .halving-line {
    width: 100%;
    height: 1px;
    background-color: #e5e7eb;
    margin: 15px 0;
  }

  .form-row {
    width: 100%;
    display: flex;
    align-items: flex-start;
  }

  .basicForm {
    width: 100%;
  }
</style>
